package model

import (
	"cloud-disk/xorm"
	"errors"
	"time"
)

type UserBasic struct {
	Id        uint64
	Identity  string
	Name      string
	Password  string
	Email     string
	CreatedAt time.Time `xorm:"created"`
	UpdatedAt time.Time `xorm:"updated"`
	DeletedAt time.Time `xorm:"deleted"`
}

//TableName 指定表名
func (table UserBasic) TableName() string {
	return "user_basic"
}

func (table UserBasic) UserList() ([]*UserBasic, error) {
	users := make([]*UserBasic, 0)
	err := xorm.Xorm.Find(&users)
	if err != nil {
		return nil, err
	}

	return users, nil
}

//GetUserByNamePassword 根据用户名和密码获取用户
func (table UserBasic) GetUserByNamePassword(name, password string) (user *UserBasic, err error) {
	user = new(UserBasic)
	has, err := xorm.Xorm.Where("name = ? AND password = ?", name, password).Get(user)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, errors.New("用户名或者密码错误")
	}
	return user, err
}

//GetUserByIdentity 根据identity 获取用户
func (table UserBasic) GetUserByIdentity(identity string) (user *UserBasic, err error) {
	user = new(UserBasic)
	has, err := xorm.Xorm.Where("identity = ?", identity).Get(user)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, errors.New("参数错误")
	}
	return user, err
}

//GetUserCountByEmail 根据邮箱获取用户个数
func (table UserBasic) GetUserCountByEmail(email string) (count int64, err error) {
	count, err = xorm.Xorm.Where("email = ?", email).Count(new(UserBasic))
	if err != nil {
		return 0, err
	}

	return count, nil
}

//GetUserCountByName 根据用户名获取用户个数
func (table UserBasic) GetUserCountByName(name string) (count int64, err error) {
	count, err = xorm.Xorm.Where("name = ?", name).Count(new(UserBasic))
	if err != nil {
		return 0, err
	}

	return count, nil
}

//CreateUser 创建用户
func (table UserBasic) CreateUser(user *UserBasic) error {
	_, err := xorm.Xorm.Insert(user)
	if err != nil {
		return err
	}
	return nil
}
